package cc.sunni.controller;

import cc.sunni.entity.FaceUser;
import cc.sunni.service.FaceUserService;
import cc.sunni.utils.Base64Util;
import cc.sunni.utils.MultipartFileToFile;
import cc.sunni.utils.R;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jiangli
 * @since 2021/2/19 14:13
 */
@RestController
@RequestMapping("/bd/face")
public class BaiDuFaceController {
    @Autowired
    private FaceUserService faceUserService;

    /**
     * @param userId 用户唯一标识,电话号码,身份证号码
     */
    @PostMapping("/register")
    public R register(MultipartFile file, @RequestParam String userId) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add";
        File image = null;
        try {
            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = getAuth();

            image = MultipartFileToFile.multipartFileToFile(file);
            byte[] buff = Base64Util.getBytesFromFile(image);
            String encode = Base64Util.encode(buff);

            Map<String, Object> map = new HashMap<>();
            map.put("image", encode);
            map.put("image_type", "BASE64");
            map.put("group_id", "bht");
            map.put("user_id", userId);
            map.put("user_info", "abc");
            map.put("action_type", "REPLACE");

            url = url + "?access_token=" + accessToken;
            String body = HttpRequest.post(url)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .body(JSONUtil.toJsonStr(map))
                    .execute().body();
            JSON json = JSONUtil.parse(body);
            Integer code = json.getByPath("error_code", Integer.class);
            String msg = json.getByPath("error_msg", String.class);
            if (code == 0 && "SUCCESS".equalsIgnoreCase(msg)) {
                String faceToken = json.getByPath("result.face_token", String.class);
                FaceUser faceUser = faceUserService.getOne(new LambdaQueryWrapper<FaceUser>().eq(FaceUser::getUserId, userId));
                if (faceUser != null) {
                    faceUser.setFaceToken(faceToken);
                    faceUserService.updateById(faceUser);
                } else {
                    FaceUser user = new FaceUser();
                    user.setUserId(userId);
                    user.setPassword("123456");
                    user.setFaceToken(faceToken);
                    user.setAvatar("xx.jpg");
                    faceUserService.save(user);
                }
                return R.ok(faceToken);
            } else {
                return R.error(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("人脸注册异常");
        } finally {
            // 删除缓存图片
            MultipartFileToFile.delteTempFile(image);
        }
    }

    @PostMapping("/login")
    public R login(MultipartFile file) {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/multi-search";
        File image = null;
        try {
            image = MultipartFileToFile.multipartFileToFile(file);
            byte[] buff = Base64Util.getBytesFromFile(image);
            String encode = Base64Util.encode(buff);

            Map<String, Object> map = new HashMap<>();
            map.put("image", encode);
            map.put("image_type", "BASE64");
            map.put("group_id_list", "bht");

            String accessToken = getAuth();
            url = url + "?access_token=" + accessToken;
            String body = HttpRequest.post(url)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .body(JSONUtil.toJsonStr(map))
                    .execute().body();
            JSON json = JSONUtil.parse(body);
            Integer code = json.getByPath("error_code", Integer.class);
            String msg = json.getByPath("error_msg", String.class);
            if (code == 0 && "SUCCESS".equalsIgnoreCase(msg)) {
                String userId = json.getByPath("result.face_list[0].user_list[0].user_id", String.class);
                FaceUser user = faceUserService.getOne(new LambdaQueryWrapper<FaceUser>().eq(FaceUser::getUserId, userId));
                return R.ok(user);
            } else if (code == 222207) {
                return R.error("用户未注册");
            } else if (code == 222202) {
                return R.error("图片中未检测到人脸");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 删除缓存图片
            MultipartFileToFile.delteTempFile(image);
        }
        return R.error("人脸识别异常");
    }

    /**
     * 获取权限token
     */
    public static String getAuth() {
        String clientId = "RmccrVZutI5PPv8rS6fw4QkR";
        String clientSecret = "DMQhozkG9lNKRvujhY3AgoPwGsTdFQEU";
        return getAuth(clientId, clientSecret);
    }

    /**
     * 获取API访问token
     * 该token有一定的有效期，需要自行管理，当失效时需重新获取.
     *
     * @return assess_token 示例：
     * "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
     */
    public static String getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            JSONObject jsonObject = new JSONObject(result);
            String access_token = jsonObject.getStr("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }
}
